package cn.tedu.erp.project.filter;

import cn.tedu.erp.project.security.LoginPrincipal;
import cn.tedu.erp.project.web.JsonResult;
import cn.tedu.erp.project.web.ServiceCode;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.security.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * 过滤器执行类
 */
@Slf4j
@Component
public class JwtAuthorizationFilter extends OncePerRequestFilter {
    //jwt的最小有效值
    private static final int JWT_MIN_LENGTH = 110;

    //接收yml中的值
    @Value("${erp.jwt.secret-key}")
    private String secretKey;

    //执行过滤器
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain)
            throws ServletException, IOException {
        log.debug("jwt过滤器开始执行");
        //将客户端提交的jwt放在消息头中,名为Authorization的属性
        String jwt = request.getHeader("Authorization");
        log.debug("客户端携带的jwt:{}", jwt);

        //判断客户端是否携带了有效的jwt
        if (!StringUtils.hasText(jwt) || jwt.length() < JWT_MIN_LENGTH) {
            //若无效,直接放行
            log.debug("客户端没有携带有效的jwt,将放行,由后续的过滤器继续处理请求");
            filterChain.doFilter(request, response);
            return;
        }

        //尝试解析jwt,并处理相关的异常
        Claims claims = null;
        //响应文类型
        response.setContentType("application/json;charset = utf-8");
       //解析jwt
        try {
            claims = Jwts.parser()
                    .setSigningKey(secretKey)
                    .parseClaimsJws(jwt)
                    .getBody();
        } catch (MalformedJwtException e) {
            //jwt格式错误
            String message = "非法访问!";
            log.debug("解析jwt时出现MalformedJwtException,错误信息为:{}",message);
            PrintWriter writer = response.getWriter();
            JsonResult<Void> jsonResult =
                    JsonResult.fail(ServiceCode.ERROR_MALFORMED, message);
            String jsonString = JSON.toJSONString(jsonResult);
            writer.println(jsonString);
            writer.close();
            return;
        } catch (SignatureException e) {
            //jwt数字签名验证失败
            String message = "非法访问!";
            log.debug("解析jwt时出现SignatureException,错误信息为:{}",message);
            PrintWriter writer = response.getWriter();
            JsonResult<Void> jsonResult =
                    JsonResult.fail(ServiceCode.ERROR_SIGNATURE, message);
            String jsonString = JSON.toJSONString(jsonResult);
            writer.println(jsonString);
            writer.close();
            return;
        } catch (ExpiredJwtException e) {
            //jwt过期
            String message = "你好,你的登录信息已过期!";
            log.debug("解析jwt时出现ExpiredJwtException,错误信息为:{}",message);
            PrintWriter writer = response.getWriter();
            JsonResult<Void> jsonResult =
                    JsonResult.fail(ServiceCode.ERROR_EXPIRED, message);
            String jsonString = JSON.toJSONString(jsonResult);
            writer.println(jsonString);
            writer.close();
            return;
        } catch (Throwable e) {
            //其他异常,后续更新维护优化
            String message = "服务器繁忙...(开发过程中看到此提示,请检查控制台异常抛出,并补充处理!";
            log.warn("解析jwt时出现Throwable,错误信息为{}",message);
            log.warn("异常类型:{}",e.getClass());
            log.warn("异常信息:{}",e.getMessage());
            PrintWriter writer = response.getWriter();
            JsonResult<Void> jsonResult =
                    JsonResult.fail(ServiceCode.ERROR_UNKNOWN, message);
            String jsonString = JSON.toJSONString(jsonResult);
            writer.println(jsonString);
            writer.close();
            return;
        }

        Long id = claims.get("id", Long.class);//期望的类型long
        String username = claims.get("username", String.class);//期望的类型string
        String authoritiesJsonString =
                claims.get("authoritiesJsonString", String.class);//期望的类型string
        log.debug("解析jwt结束:id={},username={},authoritiesJsonString={}", id, username, authoritiesJsonString);
        //创建当事人对象,存入到Authentication对象中
        LoginPrincipal loginPrincipal = new LoginPrincipal();
        loginPrincipal.setId(id);
        loginPrincipal.setUsername(username);
        //临时处理认证信息中的权限
        List<SimpleGrantedAuthority> authorities =
                JSON.parseArray(authoritiesJsonString, SimpleGrantedAuthority.class);
        //创建Authentication对象
        Object principal = loginPrincipal;//当事人对象
        Object credentials = null;
        Authentication authentication = new UsernamePasswordAuthenticationToken(
                principal, credentials, authorities
        );
        //将Authentication存到SecurityContext中
        SecurityContext securityContext = SecurityContextHolder.getContext();
        securityContext.setAuthentication(authentication);
        //放行
        filterChain.doFilter(request, response);
    }
}
